﻿using System;
using System.IO;
using Autofac;
using Autofac.Configuration;
using Autofac.Extensions.DependencyInjection;
using Conference.Command;
using Conference.CommandHandler;
using Conference.Common;
using Conference.Common.Consul;
using Conference.Domain;
using Conference.Domain.Repository;
using Conference.EntityFrameworkCore;
using Conference.EntityFrameworkCore.RepositoryImpl;
using Conference.QueryService;
using Conference.QueryService.EventHandler;
using log4net;
using log4net.Config;
using log4net.Repository;
using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Exceptionless;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
using ConferenceWebApi.Models;
using FluentValidation;
using System.Collections.Generic;
using Conference.Common.IocHelper;

namespace ConferenceWebApi
{
    /// <summary>
    /// Startup
    /// </summary>
    public class Startup
    {
        /// <summary>
        /// 日志Repository
        /// </summary>
        public static ILoggerRepository Repository { get; set; }

        /// <summary>
        /// Startup 构造
        /// </summary>
        /// <param name="configuration"></param>
        /// <param name="env"></param>
        public Startup(IConfiguration configuration, IWebHostEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                //.AddJsonFile("autofac.json")//读取autofac.json文件
                .AddEnvironmentVariables();
            Configuration = builder.Build();
            Repository = LogManager.CreateRepository("NETCoreRepository");
            XmlConfigurator.Configure(Repository, new FileInfo("log4net.config"));
        }

        /// <summary>
        /// IConfigurationRoot
        /// </summary>
        public IConfigurationRoot Configuration { get; }

        /// <summary>
        /// 注入的容器
        /// </summary>
        public IContainer Container { get; private set; }

        /// <summary>
        /// 运行时调用此方法,使用此方法将服务添加到容器
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public void ConfigureServices(IServiceCollection services)
        {
            //这里就是填写数据库的链接字符串          
            var connection = Configuration.GetSection("ConnectionService")["ConnectionSqlService"];
            services.AddDbContext<ConferenceContext>(options => options.UseSqlServer(connection));
            //注入
            DependencyInjectionService.GetInstance(services)
                .AddMvc()
                .AddCookie()
                .AddSwagger()
                .AddCap()
                .AddRedis()
                .AddFluentValidationErrorMessage();
        }

        /// <summary>
        /// 依赖注入容器
        /// </summary>
        /// <param name="builder"></param>
        public void ConfigureContainer(ContainerBuilder builder)
        {
            builder.ConfigureContainerBuilder();
            //builder.RegisterType<CreateCustomerValidator>().As<IValidator<CreateCustomerDto>>();
        }

        /// <summary>
        /// //运行时调用此方法,使用此方法配置HTTP请求管道。
        /// </summary>
        /// <param name="app"></param>
        /// <param name="env"></param>
        /// <param name="appLifetime"></param>
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime appLifetime)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            ConsulServiceEntity serviceEntity = new ConsulServiceEntity
            {
                IP = "localhost",
                Port = Convert.ToInt32(Configuration["Service:Port"]),
                ServiceName = Configuration["Service:Name"],
                ConsulIP = Configuration["Consul:IP"],
                ConsulPort = Convert.ToInt32(Configuration["Consul:Port"])
            };
            //app.RegisterConsul(appLifetime, serviceEntity);

            app.UseStaticFiles();//使用默认文件夹wwwroot       
            //启用中间件服务生成Swagger作为JSON终结点
            app.UseSwagger();

            //启用中间件服务对swagger-ui，指定Swagger JSON终结点
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");

            });

            app.UseAuthentication();

            app.UseExceptionless("EwfPHhViWoMO3yYT89s5HtCMUV6m62Wqil7NYVxL");
            //ExceptionLess日志
            //ExceptionlessClient.Default.Configuration.ApiKey = Configuration.GetSection("ExceptionLess:ApiKey").Value;
            //ExceptionlessClient.Default.Configuration.ServerUrl = Configuration.GetSection("ExceptionLess:ServerUrl").Value;

            //app.UseExceptionless();

            app.UseRouting();

            app.UseCors();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
            //释放注入的容器
            appLifetime.ApplicationStopped.Register(() => this.Container.Dispose());

        }
    }
}
